#!/usr/bin/python
#coding=utf-8

##########################################
##session借鉴入职前作业示例网站的思路实现#
##########################################


from db.db_utils import DBUtils
import pickle
import base64
import time
import datetime
import uuid
import utils.log_utils as log

class MysqlStore(object):
    def __init__(self):
        self.db = DBUtils()

    def contains(self, key):
        sql = "SELECT * FROM session WHERE session_id = %s"
        rows = self.db.execute(sql, (key, ))
        if rows:
            return bool(rows[0])
        else:
            return False

    def get(self, key):
        now = time.strftime("%Y-%m-%d %H:%M:%S")
        sql = "SELECT data FROM session WHERE session_id = %s"
        rows = self.db.execute(sql, (key, ))
        if rows:
            data = rows[0][0]
            sql = "UPDATE session SET atime = %s WHERE session_id = %s"
            self.db.execute(sql, (now, key))
            return self.decode(data)
        return None

    def set(self, key, value):
        pickled = self.encode(value)
        if self.contains(key):
            sql = "UPDATE session SET data = %s WHERE session_id = %s"
            self.db.execute(sql, (pickled, key))
        else:
            sql = "INSERT INTO session(session_id, data) VALUES (%s, %s)"
            self.db.execute(sql, (key, pickled))

    def delete(self, key):
        sql = "DELETE FROM session WHERE session_id = %s"
        self.db.execute(sql, (key, ))

    def encode(self, session_dict):
        pickled = pickle.dumps(session_dict)
        return base64.encodestring(pickled)

    def decode(self, session_data):
        pickled = base64.decodestring(session_data)
        return pickle.loads(pickled)

class Session(object):
    def __init__(self, request, store=MysqlStore()):
        self._data = {}
        self.request = request
        self.store = store 
        s_id = request.cookie().get("s_id")                                                               
        if s_id:                                                                                            
            s_id = s_id.value                                                                         
        else:
            s_id = None
        self.load(s_id)

    def __contains__(self, name):
        return name in self._data 

    def __setitem__(self, name, value):
        self._data[name] = value

    def __getitem__(self, name):
        return self._data[name]

    def get(self, name):
        if self._data.has_key(name):
            return self._data[name]
        else:
            return None

    def load(self, s_id = None):
        self.s_id, self.new = s_id, False
        if not self.s_id:
            self.new = True
            self.s_id = self.generate_session_id()
        self._data = self.store.get(s_id) or dict() 

    def save(self):
        self.store.set(self.s_id, self._data)

    def generate_session_id(self):
        s_id = "".join(uuid.uuid4().hex for i in xrange(2))
        return s_id

    def is_new(self):
        return self.new

    def invalidate(self):
        self.store.delete(self.s_id)

    





        

        




